package com.icecloud.cloud.upms.conf.mybatis;

import javax.annotation.PreDestroy;
import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@MapperScan("com.icecloud.cloud.upms")
@EnableTransactionManagement
public class MybatisDataSource implements EnvironmentAware {

	// mybaits mapper xml搜索路径
	private final static String MAPPERLOCATIONS = "classpath:/mybatis/mappings/**/*.xml";
	private final static String CONFIGLOCATION = "classpath:/mybatis/mybatis-config.xml";

	private RelaxedPropertyResolver propertyResolver;
    
    public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
    }
	
	
	private DruidDataSource datasource = null;

	@Bean(destroyMethod = "close")
	public  DataSource dataSource(){
		datasource = new DruidDataSource();  
		datasource.setUrl(propertyResolver.getProperty("url"));
		datasource.setDbType(propertyResolver.getProperty("type"));
		datasource.setDriverClassName(propertyResolver.getProperty("driver"));
		datasource.setUsername(propertyResolver.getProperty("username"));
		datasource.setPassword(propertyResolver.getProperty("password"));
		return datasource;
	}

	@PreDestroy
	public void close() {
		if(datasource != null){
			datasource.close();
		}
	}

	@Bean
	public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource());
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources(MAPPERLOCATIONS));
		sqlSessionFactoryBean.setConfigLocation(resolver.getResource(CONFIGLOCATION));
		sqlSessionFactoryBean.setTypeAliasesPackage("com.icecloud.cloud.upms");
		
		return sqlSessionFactoryBean.getObject();
	}

	@Bean
	public PlatformTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource());
	}
	

}
